//////////////////////////////////
// Gregory R McNeil
//
// Qantm College Final Project
// Snowboarding Game
//////////////////////////////////
#include "Texture.h"

Texture::Texture()
{
	m_texID = -1;
	m_width = 0;
	m_height = 0;
}

Texture::~Texture()
{
}

void Texture::Unload()
{
	if (m_texID != -1)
	{
		//had this commented out because of funny quit condition
		glDeleteTextures(1,&m_texID);
	}
}
void Texture::CreateFromData(unsigned char *data, int width, int height, int bytesPerPixel)
{
	glGenTextures(1, &m_texID);
	glBindTexture(GL_TEXTURE_2D, m_texID);

	int format = GL_RGB;
	if (bytesPerPixel == 4)
	{
		format = GL_RGBA;
	}

	/*Copying the SDL texel data on to OpenGl*/
	glTexImage2D(GL_TEXTURE_2D,
		0,
		format,
		width,
		height,
		0,
		format,
		GL_UNSIGNED_BYTE,
		data);
	gluBuild2DMipmaps(
		GL_TEXTURE_2D,
		format,
		width,
		height,
		format,
		GL_UNSIGNED_BYTE,
		data);

	/*Setting up Filtering*/
	glTexParameterf(
		GL_TEXTURE_2D,
		GL_TEXTURE_MAG_FILTER,
		GL_NEAREST);

	glTexParameterf(
		GL_TEXTURE_2D,
		GL_TEXTURE_MIN_FILTER,
		GL_NEAREST);

	/*Enable Texturing*/
	glEnable(GL_TEXTURE_2D);

}

bool Texture::Load(const std::string &filename)
{
	SDL_Surface* surf = 
		IMG_Load(filename.c_str());
	assert(surf);
	/*Extracting the data from the SDL surface*/
	unsigned char* data = (unsigned char*)surf->pixels;

	m_width = surf->w;
	m_height = surf->h;
	int bpp = surf->format->BytesPerPixel;

	CreateFromData(data, m_width, m_height, bpp);
	/*SDL Surf no-longer needed*/
	SDL_FreeSurface(surf);

	return true;
}

void Texture::UseThisTexture()
{

	glBindTexture(GL_TEXTURE_2D, m_texID);
}

void Texture::EnableSphereMapping()
{
	glTexGeni(
		GL_S,
		GL_TEXTURE_GEN_MODE,
		GL_SPHERE_MAP);

	glTexGeni(
		GL_T,
		GL_TEXTURE_GEN_MODE,
		GL_SPHERE_MAP);

	glEnable(GL_TEXTURE_GEN_S);
	glEnable(GL_TEXTURE_GEN_T);
}

void Texture::DrawTexQuad()
{
	UseThisTexture();

	glBegin(GL_QUADS);
	glNormal3f(0,0,1);
	glTexCoord2f(0,1);
	glVertex3f(-50.0f, 0.0f, -50.0f);

	glTexCoord2f(0,0);
	glVertex3f(100.0f, 0.0f, -50.0);

	glTexCoord2f(1,0);
	glVertex3f(50.0f, 0.0f,  50.0f);

	glTexCoord2f(1,1);
	glVertex3f(-50.0f, 0.0f,  50.0f);
	glEnd();
}
